package com.dnjn.happiness.system.controller;


import com.dnjn.happiness.biz.api.RemoteOutletService;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.HxBeanSeed;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.core.constant.Constants;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.security.service.TokenService;
import com.dnjn.happiness.emo.api.RemoteEmoUserService;
import com.dnjn.happiness.oss.api.RemoteMinioService;
import com.dnjn.happiness.system.api.domain.SysTeam;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.system.api.model.LoginUser;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.system.model.SysUserDTO;
import com.dnjn.happiness.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * 个人信息 业务处理
 *
 * @author happy
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RemoteEmoUserService hxBeanService;

    @Autowired
    private RemoteMinioService minioController;

    @Autowired
    private ISysTeamService teamService;

    @Autowired
    private RemoteOutletService outletService;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 个人信息
     */
    @GetMapping("getUserProfileByUserId/{userId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getUserProfileByUserId(@PathVariable Long userId) {
        Assert.notNull(userId, "用户Id不能为空");
        SysUser user = userService.selectUserById(userId);
        SysTeam parentTeam = teamService.getParentInfoByUserId(userId);
        if (!Objects.isNull(parentTeam) && !Objects.isNull(parentTeam.getNickName())) {
            user.setParentTeamName(parentTeam.getNickName());
        }

        AjaxResult ajax = AjaxResult.success(SysUserDTO.iconv(user));

        ajax.put("roleGroup", userService.selectUserRoleGroup(user.getUserName()));
        ajax.put("postGroup", userService.selectUserPostGroup(user.getUserName()));
        ajax.put("outlet", outletService.getLastOutletByUserId(userId,SecurityConstants.INNER));
        return ajax;
    }

    /**
     * 微信小程序获取个人信息
     */
    @GetMapping("wxGetProfile")
    public AjaxResult wxGetProfile() {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        AjaxResult ajax = AjaxResult.success(SysUserDTO.iconv(user));
        return ajax;
    }
    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = loginUser.getUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        currentUser.setMarriageCondition(user.getMarriageCondition());
        currentUser.setChildrenConditionBoy(user.getChildrenConditionBoy());
        currentUser.setChildrenConditionGirl(user.getChildrenConditionGirl());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(username, newPassword) > 0)
        {
            // 更新缓存用户密码
            LoginUser loginUser = SecurityUtils.getLoginUser();
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }


    /**
     * 头像上传
     */
    @Deprecated
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String avatar = "";
            AjaxResult avatarUrlResult = minioController.uploadAvatarMinio(file, SecurityConstants.INNER);
            if(StringUtils.isNotNull(avatarUrlResult) && StringUtils.isNotNull(avatarUrlResult.get("fileUrl"))){
                avatar = (String) avatarUrlResult.get("fileUrl");
            }
            String oldAvatar = userService.selectUserById(loginUser.getUserid()).getAvatar();
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                // 添加用户快乐豆
                if (StringUtils.isEmpty(oldAvatar)) {
                    HxBeanSeed hxBeanSeed = new HxBeanSeed();
                    hxBeanSeed.setUserId(loginUser.getUserid());
                    hxBeanSeed.setRiskType(Constants.AVATAR_HLBEAN_CODE);
                    R<Boolean> result1 = hxBeanService.updateHBean(hxBeanSeed, SecurityConstants.INNER);
                }
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }


    /**
     * wx头像上传
     */
    @Log(title = "wx用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/wxAvatar")
    public AjaxResult wxAvatar(MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String avatar = "";
            AjaxResult result = minioController.uploadMinioCommonInnerApi(file, SecurityConstants.INNER);
            if(StringUtils.isNotNull(result) && StringUtils.isNotNull(result.get("fileUrl"))){
                avatar = (String)result.get("fileUrl");
            }

            String oldAvatar = userService.selectUserById(loginUser.getUserid()).getAvatar();
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                // 添加用户快乐豆
                if (StringUtils.isEmpty(oldAvatar)) {
                    HxBeanSeed hxBeanSeed = new HxBeanSeed();
                    hxBeanSeed.setUserId(loginUser.getUserid());
                    hxBeanSeed.setRiskType("AVATAR");
                    R<Boolean> result1 = hxBeanService.updateHBean(hxBeanSeed, SecurityConstants.INNER);
                }
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }


}
